/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package TimeRecording.widgets;

import TimeRecording.tables.Employee;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;

/**
 *
 * @author dpatchett
 */
public class EmployeeComboBox extends JComboBox {

    private static Query query;
    private static List<Employee> list;

    private class EmployeeComboModel extends DefaultComboBoxModel {

        @SuppressWarnings("unchecked")
        public EmployeeComboModel(EntityManager entityManager) {
            super();
            if (list == null) {
                list = Employee.getActiveEmployees(entityManager);
            }
        }

        @Override
        public Object getElementAt(int index) {
            return list.get(index);
        }

        @Override
        public int getSize() {
            return list.size();
        }

        @Override
        public void setSelectedItem(Object anObject) {
            if (anObject != null) {
                int id = ((Employee)anObject).getEmployeeId();
                for (Employee entry : list) {
                    if (entry.getEmployeeId() == id) {
                        super.setSelectedItem(entry);
                        return;
                    }
                }
            }
            super.setSelectedItem(null);
        }
    }

    @SuppressWarnings("unchecked")
    public EmployeeComboBox(EntityManager entityManager) {
        super();
        this.setModel(new EmployeeComboModel(entityManager));
    }
}
